package jMiiEditor.myavatareditor;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.EnumSet;
import jMiiEditor.mii.Mii;


public class MyAvavatarEditorDisplay
{
    private MyAvavatarEditorAvatarId myAvavatarEditorAvatarId;
    
    public MyAvavatarEditorDisplay( Mii mii ) 
    {
        this( 
            new MyAvavatarEditorAvatarId( 
                mii,
                EnumSet.of(
                        MyAvavatarEditorAvatarId.Attrib.HIDE_SYSTEM_ID,
                        MyAvavatarEditorAvatarId.Attrib.HIDE_MII_CREATOR
                        )
                )
        );
    }

    public MyAvavatarEditorDisplay( 
            MyAvavatarEditorAvatarId myAvavatarEditorId
            ) 
    {
        this.myAvavatarEditorAvatarId = myAvavatarEditorId;
    }

    public String getURLString()
    {
        StringBuilder url = new StringBuilder();

        url.append( "http://www.myavatareditor.com/?avatar=" );
        url.append( myAvavatarEditorAvatarId.getId() );
        
        return url.toString();
    }
    
    public URI getURI() throws URISyntaxException
    {
      return new URI( getURLString() );
    }
    
    public static boolean isSupported()
    {
        try {
            if( java.awt.Desktop.isDesktopSupported() ) {
                return true;
            }
        }
        catch( NoClassDefFoundError ignore ) {
        }
        
        return false;
    }
    
    public void showMii() 
        throws  PlateformeDesktopNotSupportedException,
                JDKVersionDesktopNotSupportedException
    {
        try {
            showMiiJDK6();
        }
        catch( NoClassDefFoundError e ) {
            throw new JDKVersionDesktopNotSupportedException();
        }
    }
    
    private void showMiiJDK6() 
        throws PlateformeDesktopNotSupportedException
    {
        if( !java.awt.Desktop.isDesktopSupported() ) {
            throw new PlateformeDesktopNotSupportedException();
        }
        
        java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
    
        if( !desktop.isSupported( java.awt.Desktop.Action.BROWSE ) ) {
            System.err.println( "Desktop doesn't support the browse action (fatal)" );
            return; //TODO
        }
        
        try {
            desktop.browse( this.getURI() );
        }
        catch( URISyntaxException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch( IOException e ) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
